<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/8/25
 * Time: 9:13
 */

namespace ticket\modules\frontend\controllers;


use ticket\libs\Communal;
use ticket\libs\Curl;
use ticket\libs\PayOrder;
use ticket\libs\Tools;
use ticket\libs\Zhiyoubao\Zhiyoubao;
use ticket\modules\frontend\models\CouponLog;
use ticket\modules\frontend\models\ErrorMsg;
use ticket\modules\frontend\models\KlyChannel;
use ticket\modules\frontend\models\OrderDetails;
use ticket\modules\frontend\models\OrderInfo;
use ticket\modules\frontend\models\TicketAdditional;
use ticket\modules\frontend\models\TicketDate;
use ticket\modules\frontend\models\TicketInfo;
use ticket\modules\frontend\models\TicketQuotaRule;
use Yii;
use yii\base\Exception;
use yii\log\FileTarget;
use yii\web\Controller;

class TicketOrderController extends BasicController
{

    /** 判断是否登录
     * @return false|string
     */
    public function actionIsLogin()
    {
        $member_id = $this->member_id;
        if  (!isset($member_id) or empty($member_id)){
            return Tools::showRes(10030,'请登录');
        }
        return Tools::showRes(0,'登录完成');
    }
    
    
    
    
    /**** 门票预定接口
     * @return false|string
     */
    public function actionTicketReserve()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $tid = isset($post['tid'])?$post['tid']:'';
            if (empty($tid)){
                return Tools::showRes(10404,'参数有误');
            }
            $ticketInfoModel = new TicketInfo();
            $ticketInfo = $ticketInfoModel::ticketInfo($tid); // 获取门票信息
            $ticketDateInfoModel  = new TicketDate();
            $ticketDateInfo = $ticketDateInfoModel::ticketDate($tid,$ticketInfo);  // 获取门票日期信息
            $ticketDateList = $ticketDateInfo[0];
            $today = $ticketDateInfo[1];
            if (!isset($today) || empty($today)){
                $today = [
                    'price' => $ticketInfo['ruling_price'],
                    'inventory' => '9999',
                ];
            }
			foreach($ticketDateList as $k=>$v){
				$ticketDateList[$k]['vip_price'] = $ticketInfo['vip_price']?$ticketInfo['vip_price']:$v['ruling_price'];
			}
            $channelInfo = KlyChannel::getInfo($ticketInfo['channel_id']);
            return Tools::showRes(0,'success',[
                'ticketInfo' => $ticketInfo,
                'ticketDateInfo' => $ticketDateList,
//                'ticketQuota' => $ticketQuota,
                'todayPrice' => $today,
                'channelInfo' => $channelInfo,
            ]);
        }

    }



    /**** 门票下单
     * @return false|string
     */
    public function actionPreTicketOrder()
    {
        if (Yii::$app->request->isPost){
            $Communal = new Communal();
            $post = Yii::$app->request->post();
            $transaction = Yii::$app->db->beginTransaction();
            try{
                $this->checkOrderData($post);  // 校验参数是否正确
                $this->checkTicketQuota($post); // 校验用户是否符合限购规则
                $ticketInfo = (new TicketInfo())->getInfo($post['tid']);        // 获取门票详情
                $nowData = date("Y-m-d",strtotime($post['reserveTime']));
                $rulingPrice = (new TicketDate())->getPriceByDate($post['tid'],$nowData,$ticketInfo);
                if (!$rulingPrice){
                    throw new Exception('该日期没有设置门票价格');
                }
				if($post['isvip']){
					if(!$ticketInfo['vip_price'])
						throw new Exception('该门票没有设置vip购买价格');
					$check_model = OrderDetails::find()->select(['oid'])->where(['phone'=>$post['phone'],'isvip'=>1])->indexBy('oid')->asArray()->all();
					$check_is_ok = OrderInfo::find()->where(['oid'=>array_keys($check_model),'order_status'=>[1,3]])->indexBy('oid')->asArray()->all();
					$check_count = OrderDetails::find()->where(['oid'=>array_keys($check_is_ok)])->sum('ticket_num');
					$check_count = $check_count==null?0:$check_count;
					if(($check_count+$post['num'])>5)
						throw new Exception('超过该门票没vip购买次数');
					$rulingPrice = $ticketInfo['vip_price'];
				}
                $ticketInfo['total_price'] =  $rulingPrice * $post['num'];
                $ticketInfo['rulingPrice'] =  $rulingPrice;
                $orderSn = Tools::createOrder();
                $ticketInfo['postData'] = $post;

                $orderModel = new OrderInfo();
                if (!$oid = $orderModel->addOrderInfo($ticketInfo,$orderSn)){
                    throw new Exception('添加订单失败',10044);

                }
                $orderDetailsModel = new OrderDetails();
                if  (!$orderDetailsModel->addDetailsInfo($oid,$ticketInfo)){
                    throw new Exception('添加订单详情失败',10045);
                }
                $member_id = $this->member_id;
				
				// 核销优惠券， 返回实付金额
				$real_price = $Communal->verifyCoupon($post,$orderSn,$member_id,$ticketInfo,$oid);
				OrderInfo::updateAll(['real_pay' => $real_price*100],['oid' => $oid]);          // 填写真实价格
               
                TicketAdditional::updateAllCounters(['sold' => 1],['tid' => $post['tid']]);

                $transaction->commit();
                $this->startSwooleTimer($orderSn);  // 添加定时任务
                return Tools::showRes(0,'success',[
                    'order_id' => $oid,
                ]);
            }catch (Exception $e){
                $transaction->rollBack();
                ErrorMsg::setInfo($_SERVER['REQUEST_URI'],99999,'门票下单'.json_encode($ticketInfo,JSON_UNESCAPED_UNICODE),['code' => $e->getCode(),'msg' => $e->getMessage()]);
                return Tools::showRes($e->getCode(),$e->getMessage());
            }

        }

    }
	
	
	/**** 门票下单
	 * @return false|string
	 */
	public function actionPreTicketOrderMore()
	{
	    if (Yii::$app->request->isPost){
	        $Communal = new Communal();
	        $post = Yii::$app->request->post();
	        $transaction = Yii::$app->db->beginTransaction();
	        try{
	            //$this->checkOrderData($post);  // 校验参数是否正确1
				if(!is_array($post['ticketList'])){
					$post['ticketList'] = json_decode($post['ticketList'],true);
				}
				$post['is_list'] = 1;
				$params = [
					'total_price'=>0,
					'rulingPrice'=>0,
					'all_num'=>0,
				];
				foreach($post['ticketList'] as $v){
					$member_check = [
						'tid'=>$v['tid'],
						'reserveTime'=>$post['reserveTime'],
						'phone'=>$post['phone'],
						'num'=>$v['num']
					];
					$this->checkTicketQuota($member_check);// 校验用户是否符合限购规则
					$ticketInfo= (new TicketInfo())->getTicketInfo($v['tid']);
					$nowData = date("Y-m-d",strtotime($post['reserveTime']));
					$rulingPrice = (new TicketDate())->getPriceByDate($v['tid'],$nowData,$ticketInfo);
					if (!$rulingPrice){
					    throw new Exception('该日期没有设置门票价格');
					}
					$params['total_price'] =  $params['total_price']+($rulingPrice * $v['num']);
					$params['rulingPrice'] =  $params['rulingPrice']+($rulingPrice * $v['num']);
					$params['ticket_json'][]=[
						'goods_name'=>$ticketInfo['name'],
						'num'=>$v['num'],
						'image'=>$ticketInfo['additional']['image_url']?$ticketInfo['additional']['image_url']:'',
						'total_price'=>$rulingPrice * $v['num'],
						'rulingPrice'=>$rulingPrice,
						'ticket_sn'=>$nowData==date('Y-m-d',time())?$ticketInfo['now_ticket_sn']:$ticketInfo['ticket_sn'],
					];
					$params['aid'] = $ticketInfo['aid'];
					$params['app_id'] = $ticketInfo['app_id'];
					$params['all_num'] = $params['all_num']+$v['num'];
					
				}
				
	            //$this->checkTicketQuota($post); // 校验用户是否符合限购规则
	            // $ticketInfo = (new TicketInfo())->getInfo($post['tid']);        // 获取门票详情
	            // $nowData = date("Y-m-d",strtotime($post['reserveTime']));
	            // $rulingPrice = (new TicketDate())->getPriceByDate($post['tid'],$nowData,$ticketInfo);
	            // if (!$rulingPrice){
	            //     throw new Exception('该日期没有设置门票价格');
	            // }
	            // $ticketInfo['total_price'] =  $rulingPrice * $post['num'];
	            // $ticketInfo['rulingPrice'] =  $rulingPrice;
	            $orderSn = Tools::createOrder();
	            $params['postData'] = $post;
	
	            $orderModel = new OrderInfo();
				//$oid = $orderModel->addOrderInfo($params,$orderSn);
				//throw new Exception(json_encode($oid),10044);
	            if (!$oid = $orderModel->addOrderInfo($params,$orderSn)){
	                throw new Exception('添加订单失败',10044);
	
	            }
	            $orderDetailsModel = new OrderDetails();
	            if  (!$orderDetailsModel->addDetailsInfo($oid,$params)){
	                throw new Exception('添加订单详情失败',10045);
	            }
	            $member_id = $this->member_id;
				
				// 核销优惠券， 返回实付金额
				//$real_price = $Communal->verifyCoupon($post,$orderSn,$member_id,$ticketInfo,$oid);
				$real_price = $params['total_price'];
				OrderInfo::updateAll(['real_pay' => $real_price*100],['oid' => $oid]);          // 填写真实价格
	           
	            //TicketAdditional::updateAllCounters(['sold' => 1],['tid' => $post['tid']]);
	
	            $transaction->commit();
	            $this->startSwooleTimer($orderSn);  // 添加定时任务
	            return Tools::showRes(0,'success',[
	                'order_id' => $oid,
	            ]);
	        }catch (Exception $e){
	            $transaction->rollBack();
	            ErrorMsg::setInfo($_SERVER['REQUEST_URI'],99999,'门票下单'.json_encode($params,JSON_UNESCAPED_UNICODE),['code' => $e->getCode(),'msg' => $e->getMessage()]);
	            return Tools::showRes($e->getCode(),$e->getMessage());
	        }
	
	    }
	
	}
	
	

    /*** 订单详情
     * @return false|string
     */
    public function actionGetOrderInfo()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();

            $orderId = isset($post['orderId'])?$post['orderId']:'';
            if (empty($orderId)){
                return Tools::showRes(10404,'参数有误');
            }

            $orderInfo =  (new OrderInfo())->getOrderInfo($orderId);            // 获取订单信息

            $expireTime = (strtotime($orderInfo['create_time'])+600) - time();
            if ($expireTime < 0 and $orderInfo['order_status'] == 1){
                OrderInfo::updateAll(['order_status' => 2],['oid' => $orderInfo['oid']]);
                $data['order_status'] = 2;
            }
            $ticketInfo = (new TicketInfo())->getTicketInfo($orderInfo['tid']);                 // 门票信息
            $orderInfo['details']['price'] = $orderInfo['order_amount']/$orderInfo['goods_num'];
			$orderInfo['ticket_json'] = json_decode($orderInfo['ticket_json'],true);
			if($orderInfo['ticket_json']){
				foreach($orderInfo['ticket_json'] as $k=>$v){
					$info = TicketInfo::find()->where(['or',['now_ticket_sn'=>$v['ticket_sn']],['ticket_sn'=>$v['ticket_sn']]])->asArray()->one();
					$orderInfo['ticket_json'][$k]['category'] = $info?$info['category']:'';
				}
			}
            return Tools::showRes(0,'success',[
                'orderInfo' => $orderInfo,
                'ticketInfo' => $ticketInfo,
                'expireTime' => $expireTime,
            ]);

        }
    }



    /*** 门票订单列表
     * @return false|string
     */
    public function actionUserTicketList()
    {
        if  (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $openid = isset($post['openid'])?$post['openid']:'';

            if (empty($openid)){
                return Tools::showRes(10404,'参数有误');
            }
            $orderInfoModel = new OrderInfo();
            $orderList = $orderInfoModel::orderInfo($openid,$post);
            return Tools::showRes(0,'success',$orderList);

        }

    }

    

    /**** 门票支付
     * @return bool|false|mixed|string
     */
    public function actionPayOrderInfo()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();

            $orderId = isset($post['orderId'])?$post['orderId']:'';
            $openid = isset($post['openid'])?$post['openid']:'';
            if (empty($orderId)){
                return Tools::showRes(10404,'参数有误');
            }
            $orderInfoModel = new OrderInfo();
            $orderInfo = $orderInfoModel::payOrderInfo($openid,$orderId);
            $payOrderParams = (new PayOrder())->perOrder($orderInfo);

            if (!$payOrderParams){
                return Tools::showRes(10500,'支付参数未配置');
            }
            return $payOrderParams;
        }
    }


    /**** 门票支付ali
     * @return bool|false|mixed|string
     */
    public function actionAliPayOrderInfo()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();

            $orderId = isset($post['orderId'])?$post['orderId']:'';
            $userid = isset($post['userid'])?$post['userid']:'';
            if (empty($orderId)){
                return Tools::showRes(10404,'参数有误');
            }
            $orderInfoModel = new OrderInfo();
            $orderInfo = $orderInfoModel::payOrderInfo($userid,$orderId);
            $payOrderParams = (new PayOrder())->perAliOrder($orderInfo);

            if (!$payOrderParams){
                return Tools::showRes(10500,'支付参数未配置');
            }
            return $payOrderParams;
        }
    }


    /***  退票接口
     * @return false|string
     */
    public function actionRefundInfo()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $openId = isset($post['openId'])?trim($post['openId']):'';
            $orderNum = isset($post['orderNum'])?trim($post['orderNum']):'';
            $appId = isset($post['appId'])?trim($post['appId']):'';
            if (empty($orderNum) or empty($appId)){
                return Tools::showRes(10404,'参数有误');
            }
            $orderInfoModel = new OrderInfo();
            $orderInfo = $orderInfoModel->getInfo($orderNum,$appId,$openId);

            if (!empty($orderInfo)){
                $orderDetails = (new OrderDetails())->getInfo($orderInfo['tid']);
                $orderInfo['certificate'] = $orderDetails['certificate'];
                $refundNum = 'RF'.Tools::createSn();
//                $refundRes = (new PayOrder())->refundOrder($orderInfo,$refundNum); // 退款
//                if ($refundRes['code'] == 0){
//
//                }
                $this->refundTicket($orderInfo,$refundNum);                       // 退票
                $res = $orderInfoModel->setInfo($orderNum,$appId,'6',$refundNum);      // 修改订单状态
                if ($res){
                    return Tools::showRes(0,'退票成功，等待审核');
                }
            }else{
                return Tools::showRes(10405,'订单不存在');
            }

        }
    }


    public function actionTest()
    {
        $sn = Yii::$app->request->post('sn','');
        $res = $this->startSwooleTimer($sn);
        var_dump($res);
    }
    
    

    protected function checkTicketQuota($params)
    {
        $quotaInfo = TicketQuotaRule::find()->where('tid = :id',[':id' => $params['tid']])->asArray()->one();
        $ticketInventory = TicketDate::find()->where(['tid' => $params['tid'],'date' => date("Y-m-d",strtotime($params['reserveTime']))])->select(['ruling_price','inventory','id'])->asArray()->one();
        //预支付订单占用库存判断
		$in_state_order = OrderInfo::find()
		->where(['tid'=>$params['tid'],'order_status'=>1])
		->andWhere(['>=','create_time',date('Y-m-d H:i:s',time()-10*60)])
		->count();
		if (($ticketInventory['inventory']-$in_state_order) <= 0){
            throw new Exception('抱歉，该日门票已售罄，请选择其他日期',10503);
        }
        $userTicketModel = OrderDetails::find()
            ->select(["SUM(ticket_num) as num"])
            ->andFilterWhere(['phone' => $params['phone'],'tid' => $params['tid']])
            ->andWhere(['!=','verification_code',''])
            ->andFilterWhere(['between','create_time',date("Y-m-d 00:00:00"),date("Y-m-d H:i:s")]);
        $userTicketNum = $userTicketModel->asArray()->one();
        $userTicketNum['idnum']= $userTicketModel->count();


        if (($userTicketNum['num'] + $params['num']) > $quotaInfo['phone_day_num']){
            throw new Exception('单日购买数量为'.$quotaInfo['phone_day_num'].'你已超出',10503);
        }

        if ($quotaInfo['min_sta_order'] > $params['num'] || $quotaInfo['max_end_order'] < $params['num']){
            throw new Exception('该卡种每次只能购买'.$quotaInfo['min_sta_order'].'~'.$quotaInfo['max_end_order'].'张',10503);
        }

        if (($userTicketNum['idnum']) >= $quotaInfo['max_order_num']){
            throw new Exception('单日最大下单数为'.$quotaInfo['max_order_num'].'你已超出',10503);
        }

        if (!empty($quotaInfo['phone_day']) and !empty($quotaInfo['bug_ticket_num'])){
            $begin_time = strtotime($params['reserveTime'],'-'.$quotaInfo['phone_day'].'day');
            $end_time = strtotime($params['reserveTime'],'+'.$quotaInfo['phone_day'].'day');
            $userTicketNum = OrderDetails::find()
                ->select(["SUM(ticket_num) as num"])
                ->where(['between','create_time',date("Y-m-d 00:00:00",$begin_time),date("Y-m-d 00:00:00",$end_time)])
                ->andFilterWhere(['tid' => $params['tid']])
                ->andWhere(['!=','verification_code',null])
                ->andWhere(['phone' => $params['phone']])
                ->asArray()
                ->one()['num'];
            if (($userTicketNum + $params['num']) > $quotaInfo['bug_ticket_num']){
                throw new Exception('每个用户'.$quotaInfo['phone_day'].'天内可购买:'.$quotaInfo['bug_ticket_num'].'张票'.$quotaInfo['max_order_num'].'你已超出',10503);
            }
        }

        if ($quotaInfo['advance_num'] > 0){
            $reserveTime = date("Ymd",strtotime($params['reserveTime'])); // 预约的日期
            $nowTIme = date("Ymd");   // 现在的日期
            $day = $reserveTime - $nowTIme;
            if ($day < $quotaInfo['advance_num']){
                throw new Exception('该票需要提前'.$quotaInfo['advance_num'].'天预约',10503);

            }
        }

        if (!empty($quotaInfo['day_end_time'])) {
            $nowTIme = date("H:i");
            if (date("Y-m-d") == date("Y-m-d", strtotime($params['reserveTime']))) {  // 预定日期是今日
                $day_end_time = date("H:i",strtotime($quotaInfo['day_end_time']));
                if ($nowTIme > $day_end_time) {
                    throw new Exception('很抱歉，现在已不能购买当日票',10503);

                }
            }
        }
    }


    /****  退票
     * @param $orderInfo
     * @param $refundNum
     * @return bool
     */
    protected function refundTicket($orderInfo,$refundNum)
    {
        $zhiyoubao = new Zhiyoubao($orderInfo['aid']);
        $res = $zhiyoubao->refundTicket($orderInfo,$refundNum);
        return $res;
    }





    protected function checkOrderData($params)
    {

        if (!isset($params['reserveTime']) or empty($params['reserveTime'])){
            throw new Exception('预定日期不能为空',10404);
        }
        if (!isset($params['price']) or empty($params['price'])){
            throw new Exception('价格有误',10404);
        }
        if (!isset($params['num']) or empty($params['num'])){
            throw new Exception('预定数量不能为空',10404);
        }
        if (!isset($params['name']) or empty($params['name'])){
            throw new Exception('联系人姓名不能为空',10404);
        }
        if (!isset($params['phone']) or empty($params['phone'])){
            throw new Exception('手机号不能为空',10404);
        }
        if (!empty($params['certificate']) and  !Tools::isCreditNo($params['certificate'])){
            throw new Exception('身份证号有误',10404);
        }
        if (!isset($params['tid']) or empty($params['tid'])){
            throw new Exception('手机号不能为空',10404);
        }
        if (!isset($params['openid']) or empty($params['openid'])){
            throw new Exception('openid不能为空',10404);
        }



    }

    protected function recordText($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/coupon/use_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }


    protected function startSwooleTimer($sn)
    {
        // 测试环境
//        $res = pclose(popen('php /www/wwwroot/ticket/ticket/config/starttimer.php --sn '.$sn.'&','w'));
        // 生产环境
        $res = pclose(popen('php /www/wwwroot/ticket.raysfly.com/ticket/config/starttimer.php --sn '.$sn.' &','w'));

        return $res;
    }

    

}